from sanic.views import HTTPMethodView
from sanic.response import text, json
import time
from processing.other_func import ProToken, Sercret_all, Serialization, Random_id, date_format
import json as jn
import re
from processing.comm import menuListChuli,fenpeiRole
from processing.Sql_DataFrom import ProJosn


class A_Login(HTTPMethodView):

    def __init__(self):
        self.data = ''

    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        Sercret_obj = Sercret_all()
        data = request.json
        html_data = data
        client_ip = request.ip
        try:
            data['password'] = Sercret_obj.Md5(data['password'])
            sql = "select nickName,head_img,company_config,wx_config,user_id,storeConfig from a_users where account=%s and password=%s"
            result = db.find_all(sql, (data['username'], data['password']))

            if result:
                sql = "select nickName,head_img,company_config,wx_config,user_id,storeConfig from a_users where account=%s and password=%s and status=%s"
                result1 = db.find_all(sql, (data['username'], data['password'], 'normal'))
                if result1:
                    pass
                else:
                    return json({'code': 402, 'message': "账号被禁用!"})
                usersList = ProJosn(result, sql)

                # 查询token
                sql = """
                        select us.user_id,us.nickName,us.head_img,us.account,tn.token from a_users as us JOIN
                        token as tn on us.user_id=tn.user_id where us.account=%s and us.password=%s and tn.user_id=%s
                    """

                token = db.find_all(sql, (data['username'], data['password'], usersList[0]['user_id']))

                # 查询token校验
                if token:

                    # 重新获取token
                    token_sql = """
                            update token set token=%s,login_date=now() where user_id=%s; 
                        """

                    usersList[0]['token'] = time.time()
                    # 刷新token
                    new_token = ProToken(usersList[0])
                    db.update(token_sql, (new_token, usersList[0]['user_id']))

                    data = ProJosn(token, ['accessToken', 'nickname', 'avatar', 'username', 'refreshToken'],
                                   type='list')

                    data[0]['token'] = new_token
                    sql3 = f"insert into operation_log(user_id,visit_ip,visit_path,visit_param,visit_type,create_time ) VALUES (%s,%s,%s,%s,%s,now())"
                    db.insert(sql3, (usersList[0]['user_id'], client_ip, '/login', str(html_data), 'pc'))

                    # # 查询角色
                    # roles_sql = """
                    #     select role_id from ausers_roles where user_id=%s
                    # """
                    # roles_id = db.find_one(roles_sql, usersList[0]['user_id'])
                    # roles_sql = """
                    #     select title from authority_roles where id=%s
                    # """
                    # rolesTitle = db.find_one(roles_sql, int(roles_id[0]))

                    # data[0]['roles'] = rolesTitle
                    data[0]["accessToken"] = "access-token:admin:super-admin"
                    # return json({'code': 200, 'message': "登录成功!","success":True, 'data': data[0]})
                    return json({'code': 200, 'message': "登录成功!", "success": True, 'data': data[0]})

                else:

                    token = ProToken(usersList[0])
                    sql2 = f"insert into token(token,user_id,update_date,login_date,timestamp ) VALUES (%s,%s,now(),now(),'60*60*24')"

                    db.insert(sql2, (token, usersList[0]['user_id']))

                    data = db.find_all(sql, (data['username'], data['password'], usersList[0]['user_id']))

                    data = ProJosn(data, ['accessToken', 'nickname', 'avatar', 'username', 'refreshToken'],
                                   type='list')

                    sql3 = f"insert into operation_log(user_id,visit_ip,visit_path,visit_param,visit_type,create_time ) VALUES (%s,%s,%s,%s,%s,now())"
                    db.insert(sql3, (usersList[0]['user_id'], client_ip, '/login', str(html_data), 'pc'))
                    # # 查询角色
                    # roles_sql = """
                    #                         select role_id from ausers_roles where user_id=%s
                    #                     """
                    # roles_id = db.find_one(roles_sql, usersList[0]['user_id'])
                    # roles_sql = """
                    #                         select title from authority_roles where id=%s
                    #                     """
                    # rolesTitle = db.find_one(roles_sql, int(roles_id[0]))
                    #
                    # data[0]['roles'] = rolesTitle
                    data[0]["accessToken"] = "access-token:admin:super-admin"
                    return json({'code': 200, 'message': "登录成功!", "success": True, 'data': data[0]})

            # else:
            return json({'code': 401, 'message': "账号或密码错误！"})
        except Exception as error:

            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/login', error))

            return json({'code': 500, 'message': "后端代码出错！"})


class A_userInfo(HTTPMethodView):
    async def post(self, request):
        # 登录用户的id
        user_id = request.app.ctx.user_id
        db = request.app.ctx.db
        try:
            # 获取用户角色
            a_roles_sql = f"""
                        select a_u.phone,a_u.select_role_code,a_u.user_id,a_u.nickName,a_u.head_img,a_u.company_config,a_u.wx_config,a_u.account,a_u.register_date,ars.role_id,ars.menu_list,a_u.storeConfig,a_u.theme_config,a_u.status from a_users as a_u JOIN
                        ausers_roles as ars on a_u.user_id=ars.user_id JOIN
                        authority_roles as am on ars.role_id=am.id where ars.user_id=%s
                """
            rolesInfo = db.find_all(a_roles_sql, (user_id))
            rolesInfo = ProJosn(rolesInfo, ['phone','select_role_code','user_id', 'nickName', 'head_img', 'company_config', 'wx_config', 'account',
                                            'register_date', 'role_id', 'menu_list', 'storeConfig', 'theme_config',
                                            'status'], 'list')

            rolesInfo = rolesInfo[0]
            sql_role_list = f"""
                select id,title,name,status from authority_roles 
            """
            num = 0
            for i in rolesInfo['role_id'].split(','):
                if num == 0:
                    sql_role_list += f" where id={i} "
                else:
                    sql_role_list += f" or id={i} "
                num += 1

            if db.find_all(sql_role_list):

                roleList = ProJosn(db.find_all(sql_role_list),['id','code','name','enable'],'list')
            else:
                roleList = [{
                    "id": 2,
                    "code": "ROLE_QA",
                    "name": "普通用户",
                    "enable": True
                }]

            # 切换

            roleItem = roleList[0]

            for i in roleList:
                if i['code'] == rolesInfo['select_role_code']:
                    roleItem = i

            userInfo = {
                "code": 0,
                "message": "OK",
                "data": {
                    "user_id": user_id,
                    "username": "admin",
                    "enable": True,
                    "createTime": rolesInfo['register_date'],
                    "updateTime": rolesInfo['register_date'],
                    "profile": {
                        "id": 1,
                        "nickName": rolesInfo['nickName'],
                        "gender": True,
                        "avatar": rolesInfo['head_img'] or "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif?imageView2/1/w/80/h/80",
                        "address": True,
                        "email": True,
                        "userId": user_id,
                        "phone": rolesInfo['phone'],
                        "wx_config":rolesInfo['wx_config']
                    },
                    "roles": roleList,
                    "currentRole": roleItem
                },
                "originUrl": "/user/detail"
            }

            return json(userInfo)

        except Exception as error:
            # 获取用户角色
            a_roles_sql = f"""
                                    select a_u.select_role_code,a_u.user_id,a_u.nickName,a_u.head_img,a_u.company_config,a_u.wx_config,a_u.account,a_u.register_date,ars.role_id,ars.menu_list,a_u.storeConfig,a_u.theme_config,a_u.status from a_users as a_u JOIN
                                    ausers_roles as ars on a_u.user_id=ars.user_id JOIN
                                    authority_roles as am on ars.role_id=am.id where ars.user_id=%s
                            """
            rolesInfo = db.find_all(a_roles_sql, (user_id))
            rolesInfo = ProJosn(rolesInfo, ['select_role_code','user_id', 'nickName', 'head_img', 'company_config', 'wx_config', 'account',
                                            'register_date', 'role_id', 'menu_list', 'storeConfig', 'theme_config',
                                            'status'], 'list')
            # print(rolesInfo)
            # userinfo = Serialization(rolesInfo, db)[0]
            rolesInfo = rolesInfo[0]

            # 模拟数据
            userInfo = {
                "code": 0,
                "message": "OK",
                "data": {
                    "user_id": user_id,
                    "username": "admin",
                    "enable": True,
                    "createTime": rolesInfo['register_date'],
                    "updateTime": rolesInfo['register_date'],
                    "profile": {
                        "id": 1,
                        "nickName": rolesInfo['nickName'],
                        "gender": True,
                        "avatar": rolesInfo[
                                      'head_img'] or "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif?imageView2/1/w/80/h/80",
                        "address": True,
                        "email": True,
                        "userId": user_id,
                        "phone": rolesInfo['phone'],
                        "wx_config": rolesInfo['wx_config']
                    },
                    "roles": [{
                    "id": 2,
                    "code": "ROLE_QA",
                    "name": "普通用户",
                    "enable": True
                }],
                    "currentRole": {
                    "id": 2,
                    "code": "ROLE_QA",
                    "name": "普通用户",
                    "enable": True
                }
                },
                "originUrl": "/user/detail"
            }
            return json(userInfo)
        # return json(data)


class A_tree(HTTPMethodView):
    async def post(self, request):
        # 登录用户的id
        user_id = request.app.ctx.user_id
        select_role_code = request.app.ctx.select_role_code
        db = request.app.ctx.db
        tree = {
            "code": 0,
            "message": "OK",
            "data": [],
            # "originUrl": "/role/permissions/tree"
        }

        if user_id != 'USERXiyFEvfg0bdLaqTBr7r30iKvm39S':

            # 查询用户角色
            sql_role = """
                select role_id from ausers_roles where user_id=%s
            """
            result = []

            roleData = db.find_one(sql_role,user_id)

            if roleData:
                roleData = roleData[0]
            else:
                roleData = ""
            if roleData:
                roleData = db.find_one(sql_role, user_id)[0].split(',')
                sql_menu = """
                    select id,title,menu_list from authority_roles where
                """

                if select_role_code:
                    sql_menu += f" title='{select_role_code}' "
                else:
                    for i in range(0,len(roleData)):
                        if i == 0:
                            sql_menu += ' id=' + roleData[i]
                        else:
                            sql_menu += ' or id=' + roleData[i]

                res = db.find_all(sql_menu)
                res_role = ProJosn(res,sql_menu)
                # 获取菜单
                list1 = []
                for i in range(0,len(res_role)):
                    # 去重
                    list1.extend(res_role[i]['menu_list'])

                menu_sql = """
                   select id,frameLoading,redirect,keepAlive,menuType,name,icon,component,menuRank,parentId,path,auths,showLink,ctime,status from authority_menus where  
                """
                list1 = list(set(list1))
                if list1:
                    for i in range(0,len(list1)):
                        # print(123123,list1[i])
                        if i == 0:
                            menu_sql += ' id=' + str(list1[i])
                        else:
                            menu_sql += ' or id=' + str(list1[i])
                    menu_sql += " ORDER BY menuRank ASC "
                    menu_result = db.find_all(menu_sql)
                    result = ProJosn(menu_result, menu_sql)

                else:
                    result = [{'id': 40, 'frameLoading': 'simple', 'redirect': None, 'keepAlive': False, 'menuType': 1, 'name': '个人资料', 'icon': None, 'component': '/src/views/profile/index.vue', 'menuRank': 99, 'parentId': 0, 'path': '/profile', 'auths': 'UserProfile', 'showLink': True, 'ctime': '2024-10-19 23:52:26', 'status': False}]
        else:

            sql_find = f"""
                            select id,frameLoading,redirect,keepAlive,menuType,name,icon,component,menuRank,parentId,path,auths,showLink,ctime,status from authority_menus
                        """
            menuList = db.find_all(sql_find)
            if menuList:
                result = ProJosn(menuList, sql_find)
            else:
                result =[{'id': 40, 'frameLoading': 'simple', 'redirect': None, 'keepAlive': False, 'menuType': 1, 'name': '个人资料', 'icon': None, 'component': '/src/views/profile/index.vue', 'menuRank': 99, 'parentId': 0, 'path': '/profile', 'auths': 'UserProfile', 'showLink': True, 'ctime': '2024-10-19 23:52:26', 'status': False}]

        munuData = menuListChuli(result, db)
        tree['data'] = munuData
        # 获取菜单
        return json(tree)


class A_source(HTTPMethodView):
    async def get(self, request):
        # 登录用户的id
        user_id = request.app.ctx.user_id
        db = request.app.ctx.db

        # 处理一级菜单
        sql_find = f"""
                select id,frameLoading,redirect,keepAlive,menuType,name,icon,component,menuRank,parentId,path,auths,showLink,ctime,status from authority_menus ORDER BY menuRank ASC
            """
        menuList = db.find_all(sql_find)
        menuList = ProJosn(menuList, sql_find)
        munuData = menuListChuli(menuList,db)
        data = {
            "code": 0,
            "message":"请求成功!",
            "data":munuData
        }
        return json(data)

    # return json(data)
    # 新增
    async def put(self, request):
        db = request.app.ctx.db
        html_data = request.json
        sql_insert = """
            insert into authority_menus(frameLoading,title,menuType,name,icon,component,menuRank,parentId,path,auths,showLink,status,ctime) values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,now())
        """
        if html_data['type'] == 'MENU':
            type = 1
        else:
            type = 2

        if html_data['enable'] == True:
            enable = 1
        else:
            enable = 0
        if html_data['show'] == True:
            show = 'normal'
        else:
            show = 'destroy'

        if html_data['parentId']:
            parentId = int(html_data['parentId'])
        else:
            parentId = 0

        db.insert(sql_insert, [
            html_data['layout'],
            html_data['name'],
            type,
            html_data['name'],
            html_data['icon'],
            html_data['component'],
            html_data['order'],
            parentId,
            html_data['path'],
            html_data['code'],
            enable,
            show])

        return json({'code': 200, 'message': "请求成功", "success": True, 'data': True})

    # 编辑
    async def post(self, request):
        db = request.app.ctx.db
        id = int(request.args.get('id'))
        html_data = request.json
        sql_update = """ update authority_menus set title=%s,name=%s,path=%s,auths=%s,icon=%s,frameLoading=%s,component=%s,showLink=%s,keepAlive=%s,menuRank=%s,status=%s,ctime=now() where id=%s """
        if html_data['show']:
            status = "normal"
        else:
            status = "destroy"

        if html_data['enable']:
            enable = 1
        else:
            enable = 0

        if html_data['keepAlive']:
            keepAlive = 1
        else:
            keepAlive = ""

        db.update(sql_update,(
            html_data['name'],
            html_data['name'],
            html_data['path'],
            html_data['code'],
            html_data['icon'],
            html_data['layout'],
            html_data['component'],
            enable,
            keepAlive,
            html_data['order'],
            status,
            id
        ))

        return json({'code': 200, 'message': "修改成功!"})

    async def delete(self, request):
        user_id = request.app.ctx.user_id
        db = request.app.ctx.db

        id = request.args.get('id')
        sql_delete = """
            delete from authority_menus where id=%s
        """

        db.delete(sql_delete,(id))

        return json({'code': 200, 'message': "删除成功!"})

# 按钮权限
class A_boutton(HTTPMethodView):
    async def get(self, request):
        # 登录用户的id
        user_id = request.app.ctx.user_id
        db = request.app.ctx.db

        return json({'code': 200, 'message': "请求成功!", "success": True})

class A_role(HTTPMethodView):
    async def post(self, request):
        # 登录用户的id
        user_id = request.app.ctx.user_id
        db = request.app.ctx.db

        roleList = {
            "code": 0,
            "message": "OK",
            "data": {
                "pageData": [
                    {
                        "id": 1,
                        "code": "SUPER_ADMIN",
                        "name": "超级管理员",
                        "enable": True,
                        "permissionIds": []
                    },
                    {
                        "id": 2,
                        "code": "ROLE_QA",
                        "name": "质检员",
                        "enable": True,
                        "permissionIds": [
                            1,
                            2,
                            3,
                            4,
                            5,
                            9,
                            10,
                            11,
                            12,
                            14,
                            15
                        ]
                    }
                ],
                "total": 2
            },
            # "originUrl": "/role/page?pageNo=1&pageSize=10"
        }

        return json({'code': 200, 'message': "请求成功!", "success": True, 'data': roleList})
class A_updateUserInfo(HTTPMethodView):
    async def post(self, request):
        # 登录用户的id
        user_id = request.app.ctx.user_id
        db = request.app.ctx.db
        html_data = request.json
        sql = f"""
            update a_users set 
        """
        Sercret_obj = Sercret_all()
        # nickName = % s, password = % s, passwordstr = % s, head_img = % s, phone = % s
        sum = 0
        for i in list(html_data):
            if sum == 0:
                if i == 'password':
                    sql += f" {i}='{Sercret_obj.Md5(html_data[i])}'"
                else:
                    sql += f" {i}='{html_data[i]}'"
            else:
                if i == 'password':
                    sql += f", {i}='{Sercret_obj.Md5(html_data[i])}'"
                else:
                    sql += f", {i}='{html_data[i]}'"
            sum += 1

        sql += f" where user_id='{user_id}' "
        db.update(sql)
        # db.update(sql,(
        #     html_data['nickName'],
        #     Sercret_obj.Md5(html_data['password']),
        #     html_data['password'],
        #     html_data['head_img'],
        #     html_data['phone'],
        #     user_id
        # ))

        data = {
            'code': 200,
            'data': '请求成功',
            'message': '欢迎{}回来!'.format('大傻叉')
        }

        return json(data)
class A_userList(HTTPMethodView):
    async def get(self, request):
        # 登录用户的id
        user_id = request.app.ctx.user_id
        db = request.app.ctx.db
        pageNum = int(request.args.get('pageNum', 1))
        pageSize = int(request.args.get('pageSize', 10))
        keyword = request.args.get('keyword', '')
        a_roles_sql = f"""
                     select id,user_id,nickName,account,head_img,wx_config,phone,register_date,type,status,passwordstr,USER_SERVICE_TOKEN from a_users
                """
        tol = """ SELECT COUNT(*) FROM a_users"""

        if keyword:
            a_roles_sql += f" where  nickName LIKE '%{keyword}%' or  account LIKE '%{keyword}%' or  phone LIKE '%{keyword}%'"
            tol += f" where  nickName LIKE '%{keyword}%' or account LIKE '%{keyword}%' or phone LIKE '%{keyword}%'"
        a_roles_sql += f" ORDER BY register_date DESC "
        # 总数据
        tol_data = db.find_one(tol)

        # 分页pageNum
        if pageNum == 1:
            a_roles_sql += f" LIMIT {pageSize} "
        else:
            a_roles_sql += f" LIMIT {pageNum * pageSize - pageSize},{pageNum * pageSize} "

        rolesInfo = db.find_all(a_roles_sql)

        listName = ['id','user_id','username','account','avatar','wx_config','phone','register_date','type','enable','passwordstr','USER_SERVICE_TOKEN']

        if rolesInfo:
            rolesInfo = ProJosn(rolesInfo,listName,'list')

        # 查询角色

        for i in range(0,len(rolesInfo)):
            # print(123123,rolesInfo[i])
            find_sql_role = """
                select role_id from ausers_roles where user_id=%s
            """
            # # print(find_sql_role,rolesInfo)
            role_select = db.find_one(find_sql_role,rolesInfo[i]['user_id'])
            role_select = ProJosn(role_select,find_sql_role)
            # print(role_select)

            if role_select:
                role_str = ''
                roleList = role_select[0]['role_id'].split(',')
                if roleList:
                    for j in range(0,len(roleList)):
                        if roleList[j]:
                            if j == 0:
                                role_str += ' id='+str(roleList[j])
                            else:
                                role_str += ' or id=' +str(roleList[j])

                            find_sql_role_name = """
                                                   select title,name,id from authority_roles where
                                               """

                            find_sql_role_name += role_str

                            result = db.find_all(find_sql_role_name)

                            result = ProJosn(result, ['code', 'name', 'id'], 'list')

                            rolesInfo[i]['roles'] = result
                        else:
                            rolesInfo[i]['roles'] = []

                else:
                    rolesInfo[i]['roles'] = []
            else:
                rolesInfo[i]['roles'] = []


        data = {
            'code': 200,
            'message': '请求成功',
            'data':{
                'pageData': rolesInfo,
                'total': tol_data[0],
            }
        }
        return json(data)

    async def put(self,request):
        html_data = request.json
        db = request.app.ctx.db
        Sercret_obj = Sercret_all()
        pattern = r'^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$'
        if re.match(pattern, html_data['username']):
            pass
        else:
            return json({'code': 302, 'message': "请使用邮箱格式注册！"})

        sql1 = "select * from a_users where account=%s"
        if db.find_one(sql1, html_data['username']):
            data = {
                'code': 202,
                'message': '用户已存在!'
            }
            return json(data)

        if html_data['enable']:
            enable = 'normal'
        else:
            enable = 'destroy'

        sql = "insert into a_users(user_id,passwordstr,nickName,password,account,head_img,status,phone,type,register_date ) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,now())"
        userid = Random_id(32, 'USER')
        db.insert(sql, (
            userid,
            html_data['password'],
            html_data['username'] or '测试用户',
            Sercret_obj.Md5(html_data['password']),
            html_data['username'],
            'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fsafe-img.xhscdn.com%2Fbw1%2F9e8bd863-bf16-4647-abf0-88490ce78ced%3FimageView2%2F2%2Fw%2F1080%2Fformat%2Fjpg&refer=http%3A%2F%2Fsafe-img.xhscdn.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1692239797&t=a656713f3185954147d0d361bef4b02d',
            enable,
            '',
            'b'
        ))

        fenpeiRole(userid,db,html_data) # 分配角色

        data = {
            'code': 200,
            'message': '注册成功！',
        }
        return json(data)


    async def post(self,request):
        db = request.app.ctx.db
        Sercret_obj = Sercret_all()
        html_data = request.json
        sql="""
             update a_users set password=%s,passwordstr=%s where id=%s
        """
        password = Sercret_obj.Md5(html_data['password'])

        db.update(sql,(password,html_data['password'],int(html_data['id'])))
        data = {
            'code': 200,
            'message': '编辑成功！',
        }
        return json(data)

    async def delete(self,request):
        db = request.app.ctx.db

        id = int(request.args.get('id'))

        sql = "delete from a_users where id=%s"
        db.delete(sql, (id))
        data = {
            'code': 200,
            'message': '删除成功！',
        }
        return json(data)


class A_userDel(HTTPMethodView):
    async def delete(self, request):
        user_id = request.app.ctx.user_id
        db = request.app.ctx.db
        # 查询a端所有账号信息
        html_data = request.json

        sql = "delete from a_users where user_id=%s"

        db.delete(sql, (html_data['user_id']))

        sql1 = "select * from a_users where user_id=%s"
        if db.find_one(sql1, html_data['user_id']):
            data = {
                'code': 400,
                'message': '删除失败!'
            }
        else:
            data = {
                'code': 200,
                'message': '删除成功!'
            }

        return json(data)


class A_person_add(HTTPMethodView):
    async def put(self, request):
        # 登录用户的id
        db = request.app.ctx.db
        Sercret_obj = Sercret_all()
        # 查询a端所有账号信息
        html_data = request.json

        pattern = r'^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$'
        if re.match(pattern, html_data['account']):
            pass
        else:
            return json({'code': 302, 'message': "请使用邮箱格式注册！"})

        sql1 = "select * from a_users where account=%s"
        if db.find_one(sql1, html_data['account']):
            data = {
                'code': 401,
                'message': '用户已存在!'
            }
            return json(data)

        sql = "insert into a_users(user_id,passwordstr,nickName,password,account,head_img,status,phone,type,register_date ) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,now())"
        userid = Random_id(32, 'USER')
        db.insert(sql, (
            userid,
            html_data['password'],
            html_data['nickName'] or '测试用户',
            Sercret_obj.Md5(html_data['password']),
            html_data['account'],
            html_data[
                'head_img'] or 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fsafe-img.xhscdn.com%2Fbw1%2F9e8bd863-bf16-4647-abf0-88490ce78ced%3FimageView2%2F2%2Fw%2F1080%2Fformat%2Fjpg&refer=http%3A%2F%2Fsafe-img.xhscdn.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1692239797&t=a656713f3185954147d0d361bef4b02d',
            html_data['status'] or 'destroy',
            html_data['phone'] or '',
            html_data['type'] or 'b'
        ))

        sql1 = "select * from a_users where user_id=%s"

        # 设置默认角色
        find_sql = """
                        insert into ausers_roles(user_id,role_id,ctime) values(%s,%s,now())
                    """
        db.insert(find_sql, (userid, html_data['role_id'] or '6'))

        if db.find_one(sql1, userid):
            data = {
                'code': 200,
                'message': '添加成功!'
            }
        else:
            data = {
                'code': 400,
                'message': '添加失败!'
            }

        return json(data)
class adminUserUpdate(HTTPMethodView):
    async def post(self, request):
        user_id = request.app.ctx.user_id
        db = request.app.ctx.db
        Sercret_obj = Sercret_all()
        # 查询a端所有账号信息
        html_data = request.json
        # 如果改别人数据 查看是不是超级管理员
        if html_data['user_id'] != user_id:
            # 修改商家数据
            find_sql = """
                select role_id from ausers_roles where user_id=%s
            """
            result = db.find_one(find_sql, (user_id))
            if result[0] in ['8', '5']:
                pass
            else:
                data = {
                    'code': 400,
                    'message': '权限不够!'
                }
                return json(data)

        # 修改角色
        role_sql = """
            update ausers_roles set role_id=%s,ctime=now() where user_id=%s
        """
        db.update(role_sql, (int(html_data['role_id']), html_data['user_id']))

        # update authority_menus set title=%s,icon=%s,path=%s,redirect=%s,hidden=%s,status=%s where id=%s
        sql = "update a_users set wx_config=%s,password=%s,passwordstr=%s,account=%s,nickName=%s,head_img=%s,status=%s,type=%s,register_date=now() where user_id=%s"
        db.update(sql, (
            html_data['wx_config'],
            Sercret_obj.Md5(html_data['passwordstr']),
            html_data['passwordstr'],
            html_data['account'],
            html_data['nickName'],
            html_data[
                'head_img'] or 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fsafe-img.xhscdn.com%2Fbw1%2F9e8bd863-bf16-4647-abf0-88490ce78ced%3FimageView2%2F2%2Fw%2F1080%2Fformat%2Fjpg&refer=http%3A%2F%2Fsafe-img.xhscdn.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1692239797&t=a656713f3185954147d0d361bef4b02d',
            html_data['status'] or 'destroy',
            html_data['type'],
            html_data['user_id']
        ))

        sql1 = "select * from a_users where user_id=%s"
        if db.find_one(sql1, html_data['user_id']):
            data = {
                'code': 200,
                'message': '编辑成功!'
            }
        else:
            data = {
                'code': 400,
                'message': '编辑失败!'
            }

        return json(data)
class allocation_menus(HTTPMethodView):
    async def post(self, request):
        # 登录用户的id
        user_id = request.app.ctx.user_id
        db = request.app.ctx.db
        # 查询a端所有账号信息
        html_data = request.json

        fenpeiRole(html_data['user_id'], db, html_data)  # 分配角色

        data = {
            'message': '分配成功',
            'code': 200
        }
        return json(data)

class dashboard(HTTPMethodView):
    async def get(self, request):
        user_id = request.app.ctx.user_id
        db = request.app.ctx.db
        client_ip = request.ip
        try:
            # 登录用户的id

            sql = f"""
                    select user_id,total_number,total_cash,total_visit from dashboard where user_id=%s
                """
            dataList = db.find_all(sql, user_id)
            if dataList:
                pass
            else:
                sql1 = f"""
                        insert into dashboard(user_id,total_number,total_cash,total_visit,create_time) VALUES (%s,%s,%s,%s,now())
                    """
                db.insert(sql1, (user_id, 0, 0, 0))
                dataList = db.find_all(sql, user_id)

            dataList = ProJosn(dataList, sql, 'sql')

            # 查商家注册微信用户
            users_sql = f" SELECT COUNT(*) FROM c_users where merchant_id='{user_id}'"
            users_data = db.find_one(users_sql)
            dataList[0]['register_num'] = users_data[0]

            # 查询商家共有多少订单和订单收益
            order_sql = f" SELECT COUNT(*),SUM(total_money) FROM goods_order where merchant_id='{user_id}'"
            order_data = db.find_one(order_sql)
            dataList[0]['order_num'] = order_data[0]
            if order_data[1]:
                dataList[0]['order_total_money'] = round(order_data[1],2)
            else:
                dataList[0]['order_total_money'] = 0

            # 查询每个月收益
            order_date_sql = f"""
                SELECT MONTH(ctime) AS month, SUM(total_money) AS total_money
                FROM goods_order
                WHERE merchant_id='{user_id}'
                GROUP BY MONTH(ctime)
                ORDER BY MONTH(ctime);
            """

            # 查询每个月订单
            order_sum_sql = f"""
                SELECT MONTH(ctime) AS month, COUNT(*) AS total_money
                FROM goods_order
                WHERE merchant_id='{user_id}'
                GROUP BY MONTH(ctime)
                ORDER BY MONTH(ctime);
            """
            order_date_find = db.find_all(order_date_sql)
            order_sum_find = db.find_all(order_sum_sql)
            x, y = date_format(order_date_find)
            x1, y1 = date_format(order_sum_find,'int')
            dataList[0]['x'] = x
            dataList[0]['y'] = y
            dataList[0]['y1'] = y1
            data = {
                'code': 200,
                'data': dataList,
                'message': '请求成功!'
            }
            return json(data)
        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/dashboard', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)
